import { getToken, setToken, removeToken } from "@/utils/auth";
import { defineStore } from "pinia";
import { getInfo, updateLoginInfo } from "@/api/app_api/user"
import { oneType } from "@/api/app_api/category"
import { login, logout, wxMpOpenId, wxMpLogin } from "@/api/app_api/login"
import { trim } from '@/uni_modules/uview-plus'
const useUserStore = defineStore("user", {
  state: () => ({
    token: getToken(),
		regionCode: uni.getStorageSync('regionCode') || '',
		sellChannel: uni.getStorageSync('userInfo')?.customerType == 1 ? 1 : 2,
		mode: 1,
		user: uni.getStorageSync('userInfo') || {},
		site: {},
		isLogin: false,
		openId: '',
		categoryList: [],
		categoryId: '',
		// #ifdef MP-WEIXIN
		isTc: 0, // 是否是团餐
		// #endif
		// #ifndef MP-WEIXIN
		isTc: 0, // 是否是团餐
		// #endif
		tcCategoryId: 99,
  }),
  actions: {
    // 登录
    login(params) {
      const phone = trim(params.phone);
      const password = params.password;
      return new Promise((resolve, reject) => {
        login({
					phone,
					password
				}).then((res) => {
					setToken(res.token)
					this.isLogin = true
					this.token = res.token
					resolve(null)
				})
				.catch((error) => {
					reject(error);
				});
      });
    },
		// 微信小程序登录
		wxMpOpenId(params) {
			const _this = this
		  return new Promise((resolve, reject) => {
		    uni.login({
		      provider: 'weixin', //使用微信登录
		      success: function (wxRes) {
						wxMpOpenId({
							code: wxRes.code
						}).then((res) => {
							if (res.data) {
								_this.openId = res.data
								resolve(res.data)
							} else {
								reject(res)
							}
						}).catch((error) => {
							reject(error)
						})
		      }
		    })
		  });
		},
		wxMpLoginFun(params) {
			return new Promise((resolve, reject) => {
			  wxMpLogin(params).then((res) => {
			  	setToken(res.token)
					this.isLogin = true
			  	this.token = res.token
			  	resolve(null)
			  }).catch((error) => {
			  	reject(error)
			  })
			})
		},
    // 获取用户信息
    getUserInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
						if (res.code === 200) {
							const user = res?.data || {}
							this.user = user
							this.regionCode = user?.regionCode || uni.getStorageSync('regionCode') || ''
							if (user) {
								uni.setStorageSync('userInfo', user)
							}
							if (user?.regionCode) {
								uni.setStorageSync('regionCode', user.regionCode)
							}
							this.sellChannel = res?.data?.customerType === 1 ? 1 : 2
							resolve(res)
						} else if (res.status === 500) {
							this.logOut()
							reject(res)
						} else {
							reject(res)
						}
          })
          .catch((error) => {
            reject(error)
          });
      });
    },
    // 退出系统
    logOut() {
      return new Promise((resolve, reject) => {
        logout().then(() => {
					this.token = ''
					this.isLogin = false
					removeToken()
					resolve(null)
				})
				.catch((error) => {
					reject(error)
				})
      })
    },
		// 登录记录
		updateLogin() {
		  return new Promise((resolve, reject) => {
		    updateLoginInfo({
					lastLoginType: `${uni.getSystemInfo()?.app?.uniPlatform}-${uni.getSystemInfo()?.app?.model}`,
					lastLoginVersion: uni.getSystemInfo()?.app?.appVersion || '未知版本',
					lastLoginTime: (new Date).getTime()
				}).then((data) => {
					resolve(data)
				})
				.catch((error) => {
					reject(error)
				})
		  })
		},
		// 选择区域
		changeProvince(code) {
			if (code) {
				this.regionCode = code
			}
		},
		// 切换模式
		changeMode(mode) {
			if (mode) {
				this.mode = mode
				if (this.user?.customerType !== 1) {
					this.sellChannel = mode === 2 ? 3 : 2
				}
			}
		},
		// 选择自提点
		changeSite(site) {
			if (site) {
				this.site = site
			}
		},
		// 获取分类
		getCategory() {
			return new Promise((resolve, reject) => {
			  oneType().then((res) => {
					this.categoryList = res?.data.filter(item => {
						return (this.isTc === 1 && item.id == this.tcCategoryId) || this.isTc === 0
					}) || []
					if (this.isTc === 1) {
						this.categoryId = this.tcCategoryId
					} else if (!this.categoryId) {
						this.categoryId = this.categoryList?.[0]?.id || ''
					}
					resolve(this.categoryList)
			  }).catch((err) => {
					reject(err)
				})
			})
		}
  },
});

export default useUserStore;
